package net.maku.framework.common.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import net.maku.framework.common.entity.WxUserInfoEntity;
import org.apache.commons.lang3.StringUtils;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 */
@Slf4j
public class WeiXinUtils {

    /**
     * 获取token
     */
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/stable_token";
    /**
     * 用于获取用户的openid和session_key等信息的
     */
    private static final String CODE_SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session";
    /**
     * 获取用户的手机号
     */
    private static final String USER_PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={0}";


    public static WxUserInfoEntity getWxUserInfo(String code, String appId, String secret) {
        try {
            Map<String, String> params = new HashMap<>(16);
            params.put("appid", appId);
            params.put("secret", secret);
            params.put("grant_type", "authorization_code");
            params.put("js_code", code);

            String result = HttpGetUtil.httpRequestToString(CODE_SESSION_URL, params);
            if(StringUtils.isBlank(result)){
                log.error("获取微信session信息失败，request params:",JsonUtils.toJsonString(params));
                return null;
            }
            log.info("wx openid:{}", result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String openid = jsonObject.getString("openid");
            String unionid = jsonObject.getString("unionid");
            WxUserInfoEntity userInfoEntity = new WxUserInfoEntity();
            if(StringUtils.isBlank(openid)){
                return null;
            }
            if(StringUtils.isBlank(unionid)){
                return null;
            }
            userInfoEntity.setOpenId(openid);
            userInfoEntity.setUnionId(unionid);
            return userInfoEntity;
        }catch (Exception e){
            log.error("获取微信信息异常",e);
            return null;
        }
    }

    public static String sessoion(String code, String appId, String secret) {
        Map<String, String> params = new HashMap<>(16);
        params.put("appid", appId);
        params.put("secret", secret);
        params.put("grant_type", "authorization_code");
        params.put("js_code", code);

        String result = HttpGetUtil.httpRequestToString(CODE_SESSION_URL, params);
        log.info("wx sessionKey:{}", result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String sessionKey = jsonObject.getString("session_key");
        return sessionKey;
    }

    /**
     * 获取用户的手机号
     * @param code
     * @param appId
     * @param secret
     * @return
     */
    public static String getUserPhone(String code, String appId, String secret){
        try {
            Map<String, String> params = new HashMap<>(16);
            params.put("appid", appId);
            params.put("secret", secret);
            params.put("grant_type", "client_credential");

            String result = HttpGetUtil.doPost(TOKEN_URL, JsonUtils.toJsonString(params));
            if(StringUtils.isBlank(result)){
                log.error("获取token异常");
                return null;
            }
            log.info("token info:{}",result);

            JSONObject jsonObject = JSONObject.parseObject(result);
            //此处要做缓存
            String accessToken = jsonObject.getString("access_token");

            String url = MessageFormat.format(USER_PHONE_URL,accessToken);
            log.info("#####phoneUrl:{}",url);
            Map<String, String> reqParams = new HashMap<>(16);
            reqParams.put("code", code);
            String userPhoneResult = HttpGetUtil.doPost(url, JsonUtils.toJsonString(reqParams));
            JSONObject userObject = JSONObject.parseObject(userPhoneResult);
            Integer errcode = userObject.getInteger("errcode");
            if(errcode != 0){
                String errmsg = userObject.getString("errmsg");
                log.error("获取用户手机失败:{}",errmsg);
                return null;
            }
            JSONObject phoneInfo = userObject.getJSONObject("phone_info");
            String purePhoneNumber = phoneInfo.getString("purePhoneNumber");
            return purePhoneNumber;
        }catch (Exception e){
            log.error("获取用户手机号异常",e);
            return null;
        }
    }
}
